package com.lyn.auxiliarytool.contract;

import android.os.Handler;
import android.os.Looper;
import androidx.annotation.NonNull;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 异步
 *
 * @author longyn 2022/12/5
 * @version 1.0.0
 */
public abstract class BaseAsync<Parameters, Progress, Result> {
    private final IHandler handler;

    public BaseAsync() {
        handler = new IHandler(Looper.getMainLooper());
    }

    @SafeVarargs
    public final void execute(ThreadPoolExecutor executor, Parameters... parameters) {
        if (!"main".equals(Thread.currentThread().getName())){
            throw new Error("只能在主线程执行");
        }
        executor.execute(() -> {
            handler.post(this::onPreExecute);
            Result result = doInBackground(parameters);
            handler.post(() -> onPostExecute(result));
        });
    }

    public void onPreExecute(){

    }

    public abstract Result doInBackground(Parameters ... parameters);

    public void onProgressUpdate(Progress ... progress){

    }

    public void onPostExecute(Result result){

    }

    static class IHandler extends Handler {
        public IHandler(@NonNull Looper looper) {
            super(looper);
        }
    }
}
